//
//  AddressDetailViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/26.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import TCPickerView
import Alamofire
import PKHUD
import SwiftyJSON
import Networking
import IQKeyboardManagerSwift

class AddressDetailViewController: BaseViewController, BottomShadow , AddCornerUIRectCorner {
    

    @IBOutlet weak var morenBtn: UIButton!
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var phoneNumberTextField: UITextField!
    @IBOutlet weak var provinceButton: UIButton!
    @IBOutlet weak var cityButton: UIButton!
    @IBOutlet weak var areaButton: UIButton!
    @IBOutlet weak var detailedAddressTextView: IQTextView!
    var datas:[AddressModel] = []
    var clickBtn: UIButton!
    var addressModel: AddressModel?
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        if (addressModel?.id) != nil{
            self.setData(model: addressModel!)
        }
    }
    
    override func setNavigation() {
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_save"), style: .done, target: self, action: #selector(saveTap))
    }
    
    // MARK: - 保存
    @objc func saveTap() {
        let name :String = self.nameTextField.text!
        let phone :String = self.phoneNumberTextField.text!
        let province :String = (self.provinceButton.titleLabel?.text!)!
        let city :String = (self.cityButton.titleLabel?.text!)!
        let areas :String = (self.areaButton.titleLabel?.text!)!
        let address :String = self.detailedAddressTextView.text
        if name.isEmpty {
            self.showToast(msg:"请输入收货人")
            return
        }
        if phone.isEmpty {
            self.showToast(msg:"请输入收货联系电话")
            return
        }
        if address.isEmpty {
            self.showToast(msg:"请输入收货人详细地址")
            return
        }
        let isDefault: String = self.morenBtn.isSelected ? "1" : "0"
        let idstr :String = (addressModel?.id) == nil ? "" : (addressModel?.id)!
        self.saveData(params: ["province":province,"city":city,"county":areas,"detailedAddress":address,"name":name,"mobile":phone,"isDefault":isDefault,"id":idstr])
    }
    
    
    
    func setUI() {
        let buttons = [provinceButton, cityButton, areaButton]
        for button in buttons {
            button?.layer.cornerRadius = (button?.height)! / 2
        }
        setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        nameTextField.attributedPlaceholder = NSAttributedString(string: "收货人", attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14), NSAttributedStringKey.foregroundColor : UIColor.black])
        phoneNumberTextField.attributedPlaceholder = NSAttributedString(string: "手机号", attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14), NSAttributedStringKey.foregroundColor : UIColor.black])
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func defaultTap(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    


    @IBAction func btnClick(_ sender: UIButton) {
        clickBtn = sender
        var chooseTitle :String? = "选择省份"
        var paramers:[String:String] = ["pid":"0"]
        if sender == self.cityButton {
            if self.provinceButton.tag == 0 {
                self.showToast(msg:"请选择省份")
                return
            }
            chooseTitle = "选择城市"
            paramers = ["pid":"\(self.provinceButton.tag)"]
        }else if sender == self.areaButton {
            if self.cityButton.tag == 0 {
                self.showToast(msg:"请选择城市")
                return
            }
            chooseTitle = "选择区域"
            paramers = ["pid":"\(self.cityButton.tag)"]
        }
        
        self.showCity(parameters:paramers,title:chooseTitle!)
    }
    
    // 获取内容
    func showCity(parameters:[String:String],title:String) -> Void {
        let requesturl = "\(BaseURL)\(ciyListUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        self.datas.removeAll()
                                        var cars :[String] = []
                                        for subject in arr {
                                            let dic = subject.dictionary!
                                            let model = AddressModel(fromDic: dic)
                                            
                                            cars.append((dic["name"]?.string)!)
                                            self.datas.append(model)
                                            
                                        }
                                        let picker: TCPickerView = TCPickerView.init()
                                        picker.title = title
                                        let values = cars.map { TCPickerView.Value(title: $0) }
                                        picker.values = values
                                        picker.selection = .single
                                        picker.completion = { (selectedIndexes) in
                                            for i in selectedIndexes {
                                                if self.clickBtn == self.provinceButton {
                                                    self.provinceButton.tag = Int(self.datas[i].id!)!
                                                    self.provinceButton.setTitle(values[i].title, for: UIControlState.normal)
                                                }else if self.clickBtn == self.cityButton {
                                                    self.cityButton.tag = Int(self.datas[i].id!)!
                                                    self.cityButton.setTitle(values[i].title, for: UIControlState.normal)
                                                }else if self.clickBtn == self.areaButton {
                                                    self.areaButton.tag = Int(self.datas[i].id!)!
                                                    self.areaButton.setTitle(values[i].title, for: UIControlState.normal)
                                                }
                                            }
                                        }
                                        picker.show()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
//    func fetchInfo(parameters:[String:String]) -> Void {
//        let requesturl = "\(BaseURL)\(addressInfoUrl)"
//        Alamofire.request(requesturl, method: .get,
//                          parameters: parameters,
//                          encoding: URLEncoding.default,
//                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
//                            (response) in
//                            if(response.error == nil){
//
//                                if let result = response.result.value as? NSDictionary
//                                {
//                                    let json = JSON(result)
//                                    if json["code"].int == 1{
//                                        let dic = json["data"].dictionary!
//                                        var model = AddressModel(fromDic: dic)
//                                        self.setData(model: model)
//                                    } else{
//                                        self.showToast(msg:json["message"].string)
//                                    }
//                                }
//                            }else{
//                                print("请求失败\(String(describing: response.error))")
//                            }
//
//        }
//    }
    
    func setData(model : AddressModel) -> Void {
        self.nameTextField.text = model.name
        self.phoneNumberTextField.text = model.mobile
        self.provinceButton.setTitle(model.province, for: UIControlState.normal)
        self.cityButton.setTitle(model.city, for: UIControlState.normal)
        self.areaButton.setTitle(model.county, for: UIControlState.normal)
        self.detailedAddressTextView.text = model.detailedAddress
        if Int(model.isDefault!)! > 0 {
            self.morenBtn.isSelected = true
        }
    }
    
    func saveData(params:[String:String]) -> Void {
        let requesturl = "\(BaseURL)\(addressEditUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: params ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        NotificationCenter.default.post(name: NSNotification.Name("reloadAddress"), object: self, userInfo: nil)
                                        self.showToast(msg:json["message"].string!)
                                       self.navigationController?.popViewController(animated: true)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
}

